<template>

    <div class="d_flex flex_jc_sb mb10">
        <el-space>
            <el-button v-for="(vo,i) in topToolbar" :key="i"
                       :type="vo.type"
                       :icon="vo.icon"
                       @click="vo.event(list.selectKeys)"
                       v-auth="vo.auth"
                       plain
            >
                {{vo.title}}
            </el-button>
        </el-space>
        <el-space>
            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                <el-button circle icon="Refresh" @click="list.reload()" />
            </el-tooltip>
        </el-space>

    </div>


    <el-auto-resizer :style="{height: tableHeight}">
        <template #default="{ height, width }">
            <el-table-v2 v-loading="list.loading"
                         :columns="list.columns"
                         :data="list.items"
                         :width="width"
                         :height="height"
                         :max-height="height"
                         expand-column-key="title"
                         :row-class="rowClass"
                         fixed
            />
        </template>
    </el-auto-resizer>

    <MiDialog v-model="edit.show"
              title="权限规则">

        <admin-rule-edit :edit="edit" :list="list" />

    </MiDialog>

</template>

<script setup lang="ts">

import {
    computed,
    getCurrentInstance,
    h,
    nextTick,
    onBeforeMount,
    onMounted,
    reactive,
    ref,
    resolveComponent,
    toRefs
} from "vue";
import global from "@/dict/global";
import {makeModelAuth} from "@/utils/auth";
import {CheckboxValueType, Column, TableV2FixedDir} from "element-plus";
import {useLayoutSetStore} from "@/store/layout-set";
import Edit from "@/model/edit";
import AdminRuleEdit from "@/views/auth/adminRuleEdit.vue";
import List from "@/model/list";


const auth = makeModelAuth('auth.adminRule')
const tdWidth = global.tdWidth
const {proxy} = getCurrentInstance() as any
const layoutStore = useLayoutSetStore()
const topBarRef = ref() as any

const edit = reactive(new Edit({}))

const rowCheck = (value:any, row: any) => {
    row.checked = value
    if (value) list.selectKeys.push(row.id)
    if (row.children && row.children.length>0){
        for (let item of row.children){
            rowCheck(value, item)
        }
    }
}

// toolbar 事件
const topToolbar = [
    {
        auth: auth.add,
        type: 'success',
        icon: 'Plus',
        title: '新增',
        event: async (ids:Array<number>) => {
            edit.info = {}
            edit.show = true
        }
    },
    {
        auth: auth.del,
        title: '删除',
        type: 'danger',
        icon: 'Delete',
        event: (ids:any) => {
            list.del({
                url: `/${auth.del}`,
                ids: ids
            })
        }
    },
]

const lineToolbar = [
    {
        auth: auth.edit, title: '编辑', event: (row:any) => {
            edit.info = row
            edit.show = true
        }
    },
    {
        auth: auth.del, title: '删除', type: 'del', event: (row:any) => {
            list.del({
                url: `/${auth.del}`,
                ids: [row.id]
            })
        }
    },
]

const list = reactive(new List({
    url: `/${auth.index}`,
    columns:[
        {
            key: 'select',
            width: 50,
            cellRenderer: ({rowData}:any) => {
                const onChange = (value:any) => {
                    rowCheck(value, rowData)
                }
                return h(resolveComponent("el-checkbox"),{modelValue: rowData.checked, onChange:onChange })
            },

            headerCellRenderer: () => {
                const _data = list.items
                const onChange = (value: CheckboxValueType) => {
                    list.items = _data.map(item => {
                        rowCheck(value, item)
                        return item
                    })
                }
                const allSelected = _data.every((row) => row.checked)
                const containsChecked = _data.some((row) => row.checked)

                return h(resolveComponent("el-checkbox"), {
                    modelValue:allSelected, onChange:onChange, intermediate:containsChecked && !allSelected
                })
            },
        },
        {key:'id', dataKey:'id', title: "ID", minWidth: tdWidth.id, width: tdWidth.id},
        {key:'title', dataKey:'title', title: "标题", width: tdWidth.title, flexGrow:1},
        {key:'icon', dataKey: "icon", title: "图标", width: tdWidth.title},
        {key:'name', dataKey: "name", title: "权限(组件名称)", width: tdWidth.title, flexGrow: 1},
        {key:'path', dataKey: "path", title: "组件路径", width: tdWidth.title, flexGrow: 1},
        // {name: "component", title: "组件名称", minWidth: tdWidth.cate},
        {key:'sort', dataKey: "sort", title: "排序",  width: tdWidth.cate, align: 'center'},
        {key:'status', dataKey: "status", title: "状态", width: tdWidth.cate,
            cellRenderer:({cellData}:{cellData:any}) => {
                return h(resolveComponent('MiSwitch'),{modelValue:cellData})
            },
            align: "center"},
        // {name: "create_time", title: "添加时间", width: tdWidth.date, sort:true,},
        // {name: "update_time", title: "更新时间", width: tdWidth.date, sort:true,},
        {key:'toolbar', title: "操作", minWidth: tdWidth.min, width: tdWidth.title,
            cellRenderer:({rowData}:{rowData:any}) => {
                return h(resolveComponent('MiLineBar'), {row:rowData, data:lineToolbar})
            },
            fixed: TableV2FixedDir.RIGHT, align: 'center'},
    ],
}))


const rowClass = ({rowData}:any) => {

    switch (rowData.rule_type) {
        case 1:
            return "rule_dir"
        case 2:
            return "rule_menu"
        case 3:
            return "rule_rule"
    }
}

// const getList = async () => {
//     table.loading = true
//     let {items} = await simpleGet(`/auth.adminRule/index`)
//     table.data = items
//     table.loading = false
// }

const removeById = (id:number, data:any) => {
    for (let i=0; i<data.length; i++){
        let item = data[i]
        if (id == item.id){
            data.splice(i,1)
            break
        }else{
            if (item.children && item.children.length>0){
                removeById(id, item.children)
            }
        }

    }
}


const tableHeight = computed(() => {
    return `calc(${layoutStore.mainHeight}px - 48px)`
})

onMounted(() => {
    list.getList()
})



</script>

<style>
.rule_dir{
    color: #000;
    font-weight: bold;
}
.rule_menu{
    color: #000;
}
.rule_rule{
    color: #ec6767;
}
</style>
